<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.id ? $t('product.addNew') : $t('temp.modify')"
    :close-on-click-modal="false"
    width="584px"
    class="shop-role-add-or-update-dialog"
  >
    <div class="dialog-content">
      <el-form
        ref="dataFormRef"
        :model="dataForm"
        :rules="dataRule"
        :label-width="$t('language') === 'English' ? '150px' : '80px'"
        @submit.prevent
        @keyup.enter="onSubmit()"
      >
        <el-form-item
          :label="$t('sys.roleName')"
          prop="roleName"
        >
          <el-input
            v-model.trim="dataForm.roleName"
            :placeholder="$t('sys.roleName')"
            maxlength="20"
            show-word-limit
          />
        </el-form-item>
        <el-form-item
          :label="$t('publics.remark')"
          prop="remark"
        >
          <el-input
            v-model="dataForm.remark"
            :placeholder="$t('publics.remark')"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        <el-form-item :label="$t('sys.authorize')">
          <div class="tree-con">
            <el-tree
              ref="menuListTreeRef"
              :data="menuList"
              :props="menuListTreeProps"
              node-key="menuId"
              show-checkbox
            />
          </div>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <div
          class="default-btn"
          @click="visible = false"
        >
          {{ $t('crud.filter.cancelBtn') }}
        </div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >
          {{ $t('crud.filter.submitBtn') }}
        </div>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { treeDataTranslate } from '@/utils'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['refreshDataList'])

const menuListTreeProps = reactive({
  label: 'name',
  children: 'children'
})
const dataForm = reactive({
  id: 0,
  roleName: '',
  remark: ''
})
const dataRule = reactive({
  roleName: [
    { required: true, message: $t('sys.roleNameNoNull'), trigger: 'blur' }
  ]
})

let isSubmit = false
const menuList = ref([])
const visible = ref(false)
const dataFormRef = ref(null)
const menuListTreeRef = ref(null)
const init = (id) => {
  dataForm.id = id || 0
  isSubmit = false
  let nodeList = []
  http({
    url: http.adornUrl('/sys/shopMenu/table'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    menuList.value = treeDataTranslate(data, 'menuId', 'parentId')
    if (dataForm.id) {
      nodeList = getNode(menuList.value)
    }
  }).then(() => {
    visible.value = true
    nextTick(() => {
      dataFormRef.value?.resetFields()
      menuListTreeRef.value?.setCheckedKeys([])
    })
  }).then(() => {
    if (dataForm.id) {
      http({
        url: http.adornUrl(`/sys/shopRole/info/${dataForm.id}`),
        method: 'get',
        params: http.adornParams()
      }).then(({ data }) => {
        dataForm.roleName = data.roleName
        dataForm.remark = data.remark
        const selectMenuIdList = data.menuIdList.filter(x => !nodeList.includes(x))
        menuListTreeRef.value?.setCheckedKeys(selectMenuIdList)
      })
    }
  })
}

// 查找菜单节点id
const getNode = (list) => {
  const res = []
  list.forEach(item => {
    if (item.children) {
      res.push(item.menuId, ...getNode(item.children))
    }
  })
  return res
}

// 表单提交
const onSubmit = () => {
  const menuIdList = [].concat(menuListTreeRef.value.getCheckedKeys(), menuListTreeRef.value?.getHalfCheckedKeys())
  if (!menuIdList.length) {
    return ElMessage({
      message: $t('sys.pleaseSelectAuth'),
      type: 'warning',
      duration: 1500
    })
  }
  dataFormRef.value?.validate((valid) => {
    if (valid) {
      if (isSubmit) {
        return false
      }
      isSubmit = true
      http({
        url: http.adornUrl('/sys/shopRole'),
        method: dataForm.id ? 'put' : 'post',
        data: http.adornData({
          roleId: dataForm.id || undefined,
          roleName: dataForm.roleName,
          remark: dataForm.remark,
          menuIdList
        })
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      }).catch(() => {
        isSubmit = false
      })
    }
  })
}

defineExpose({
  init
})

</script>

<style lang="scss" scoped>
.shop-role-add-or-update-dialog {
  &:deep(.el-dialog__body) {
    padding-bottom: 10px;
  }
  &:deep(.dialog-content) {
    height: auto;
    .el-form-item.el-form-item--small:last-child {
      margin-bottom: 0;
    }
    .tree-con {
      max-height: 410px;
      overflow-y: scroll;
    }
    .tree-con::-webkit-scrollbar {
      width: 6px;
      height: 1px;
      border-radius: 4px;
      background: #f7f8fa;
    }
    .tree-con::-webkit-scrollbar-thumb {
      background: #e9ecf3;
      border-radius: 4px;
    }
  }
  .tree-con {
      flex: 1;
    }
}
</style>
